package me.numark;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.Map;

import me.numark.model.LogInResponse;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.Constants;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;
import me.numark.utils.Utils;

/**
 * Created by tian on 14-9-20:下午10:14.
 */
public class AuthenticatorActivity extends BaseActivity implements WeiboAuthListener, IUiListener {

    public static final int EXISTED_USER_ERROR = 2005;

    private static final String TAG = AuthenticatorActivity.class.getName();

    protected static final String VALUE_HUXIU = "huxiu";

    protected static final String VALUE_SINA = "2";

    protected static final String VALUE_QQ = "3";

    protected static final String KEY_TOKEN = "token";

    protected static final String KEY_OPEN_ID = "openid";

    protected static final String KEY_USERNAME = "username";

    protected static final String KEY_PASSWORD = "password";

    protected static final String KEY_EMAIL = "email";

    protected static final int REQUEST_CODE_BIND_OR_REGISTER = 1;

    protected static final int REQUEST_CODE_COMPLETE_INFO = 2;

    protected WeiboAuth mWeiboAuth;

    protected Oauth2AccessToken accessToken;

    protected SsoHandler mSsoHandler;

    protected Tencent mTencent;

    protected IWXAPI mWxApi;
    private String errorMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTencent();
        initWeibo();
        initWeixin();
    }

    private void initWeixin() {
        mWxApi = WXAPIFactory.createWXAPI(this, Constants.WECHAT_KEY);
    }

    protected void initTencent() {
        try {
            mTencent = Tencent.createInstance(Constants.TencentAppId, getApplicationContext());
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    protected void initWeibo() {
        mWeiboAuth = new WeiboAuth(this, Constants.SinaAppKey, Constants.SinaAppRedirectURI,
                Constants.SinaScope);
        mSsoHandler = new SsoHandler(this, mWeiboAuth);
    }


    @Override
    public void onComplete(Object o) {
        JSONObject object = (JSONObject) o;
        try {
            LogUtils.d(TAG, "onTencentComplete, object is " + object.toString());
            String token = object.optString("access_token");
            String openId = object.optString("openid");
            String expireTime = object.optString("expires_in");
            Oauth2AccessToken qqAccessToken = new Oauth2AccessToken(token, expireTime);
            if (qqAccessToken.isSessionValid()) {
                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new java.util.Date
                        (qqAccessToken
                                .getExpiresTime()));
                LogUtils.d(TAG, "QQ log in, expire date is " + date);
                Settings.saveQQAccessToken(qqAccessToken);
                Settings.saveQQUid(openId);
            }
            Settings.saveQQLogInfo(object.toString());
            if (this instanceof LogInActivity || this instanceof RegisterActivity) {
                Map<String, String> params = new LinkedHashMap<String, String>();
                params.put("type", VALUE_QQ);
                params.put("username", openId);
                params.put("password", token);
                doLogIn(params);
            } else if (this instanceof SettingActivity) {
                //TODO
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(UiError uiError) {
        LogUtils.d(TAG,
                "onError, uiError is " + uiError.errorDetail + ", " + uiError.errorMessage);
        Toast.makeText(this,
                TextUtils.isEmpty(uiError.errorMessage) ? getString(R.string.qq_log_in_failed)
                        : uiError.errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onComplete(Bundle bundle) {
        try {
            accessToken = Oauth2AccessToken.parseAccessToken(bundle);
            LogUtils.d(TAG,
                    "onComplete, accessToken is " + accessToken.getUid() + ":" + accessToken
                            .getToken() + ", expireTime is " + accessToken.getExpiresTime());
            if (accessToken.isSessionValid()) {
                String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
                        .format(new java.util.Date(accessToken.getExpiresTime()));
                LogUtils.d(TAG, "weibo log in, expire date is " + date);
                Settings.saveWeiboAccessToken(accessToken);
                Settings.saveWeiboUid(accessToken.getUid());
                if (this instanceof LogInActivity || this instanceof RegisterActivity) {
                    showProgress(R.string.logging_in);
                    Map<String, String> params = new LinkedHashMap<String, String>();
                    params.put("type", VALUE_SINA);
                    params.put("username", accessToken.getUid());
                    params.put("password", accessToken.getToken());
                    doLogIn(params);
                } else if (this instanceof SettingActivity) {
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, getString(R.string.log_in_failed), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onWeiboException(WeiboException e) {
        LogUtils.d(TAG, "e.message is " + e.getLocalizedMessage());
        e.printStackTrace();
        Toast.makeText(this, String.format(getString(R.string.weibo_error), e.getMessage()),
                Toast.LENGTH_LONG).show();

    }

    @Override
    public void onCancel() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_CODE_BIND_OR_REGISTER
                || requestCode == REQUEST_CODE_COMPLETE_INFO) && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
            return;
        }
        // sso 授权回调
        try {
            if (mSsoHandler != null) {
                mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doLogIn(Map<String, String> params) {
        GsonRequest<LogInResponse> request = new GsonRequest<LogInResponse>(
                NetworkConstants.LOG_IN_URL, Request.Method.POST, LogInResponse.class,
                false, params, new Response.Listener<LogInResponse>() {
            @Override
            public void onResponse(LogInResponse resp) {
                dismissProgress();
                Context context = AuthenticatorActivity.this;
                if (resp.ret && resp.data != null) {
                    Settings.saveLogInInfo(Integer.toString(resp.data.uid),
                            resp.data.token);
                    Settings.saveNick(resp.data.nick);
                    Settings.saveDescription(resp.data.des);
                    Settings.setAvatar(resp.data.pic);
                    Settings.saveProfile(resp.data.toString());
                    Toast.makeText(context, R.string.log_in_success, Toast.LENGTH_SHORT).show();
                    if (true) {
                        startActivity(new Intent(context, MainActivity.class));
                        finish();
                    } else {
                        Intent intent = new Intent(context, RegisterActivity.class);
                        intent.putExtra(Constants.REGISTER_STAGE_EXTRA, resp.data.status);
                        startActivity(intent);
                    }
                } else {
                    Utils.showToast(resp.msg);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                //TODO
                dismissProgress();
                LogUtils.d(volleyError.toString());
                Utils.showToast(R.string.generic_network_error);
            }
        });
        NetworkHelper.getInstance().getRequestQueue().add(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }
}
